import axios from 'axios'
// import { Message, MessageBox } from 'element-ui'
import { Message } from 'element-ui'
// import store from '../store'
import { getToken } from '@/utils/auth'

const baseUrl = 'https://sjkg-wx-service.icaremgt.com' // 正式
// const baseUrl = 'https://api-wx-service.check.icaremgt.com' // 开发

// 创建axios实例
const service = axios.create({
  baseURL: baseUrl, // 本地
  timeout: 60000 // 请求超时时间
  // withCredentials: true
})
// request拦截器
service.interceptors.request.use(config => {
  console.log('TOKEN=' + getToken())
  if (getToken()) {
    config.headers['x-token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    console.log(res)
    if (res.value === false && res.code !== 202 && res.code !== '202') {
      Message({
        message: '操作失败!',
        type: 'error',
        duration: 5 * 1000
      })
    }
    if (res.code) {
      if (res.code !== 200 && res.code !== '200' && res.code !== 202 && res.code !== '202') {
        if (res.msg) {
          Message({
            message: res.msg,
            type: 'error',
            duration: 5 * 1000
          })
        } else if (res.message) {
          Message({
            message: res.message,
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          Message({
            message: '操作失败!',
            type: 'error',
            duration: 5 * 1000
          })
        }
      }
    }
    if (res.type === 'Error') {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      return res
    }
  },
  error => {
    console.log('错误' + error)// for debug
    if (error.message === 'timeout of 15000ms exceeded') {
      Message({
        message: '网络超时啦！',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
    if (error.message === 'Network Error') {
      Message({
        message: '服务器错误！',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
    if (error.message) {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
